<template>
  <div class="body">
    <div class="content">
      <div class="search_box">
        <el-form label-width="auto" :model="search" class="search_form ">
          <el-form-item label="用户名称" label-position="top">
            <el-input v-model="search.title" placeholder="请输入用户名称" class="search_input input_height" @input="searchData" />
          </el-form-item>
          <el-form-item label="创建时间" label-position="top">
            <el-date-picker type="daterange" v-model="search.time" size="default" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY/MM/DD" value-format="YYYY-MM-DD" unlink-panels
              @change="searchData"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div class="line"></div>
      <div class="operateBtn">
        <el-button type="primary" @click="prompt">导出</el-button>
        <div class="btnGroup">
          <el-button @click="filterData(0)">全部</el-button>
          <el-badge :value="data.filter((item) => item.status == 1).length" class="item" @click="filterData(1)">
            <el-button class="button_height">待付款</el-button>
          </el-badge>
          <el-badge :value="data.filter((item) => item.status == 2).length" class="item" @click="filterData(2)">
            <el-button class="button_height">待核销</el-button>
          </el-badge>
          <el-badge :value="data.filter((item) => item.status == 3).length" class="item" @click="filterData(3)">
            <el-button class="button_height">已核销</el-button>
          </el-badge>
          <el-badge :value="data.filter((item) => item.status == 4).length" class="item" @click="filterData(4)">
            <el-button class="button_height">已取消</el-button>
          </el-badge>
        </div>
      </div>
      <el-table :data="pageCount" style="width: 100%" class="table" @selection-change="checkall">
        <el-table-column type="selection" />
        <el-table-column prop="shoptitle" label="店铺名称" align="center">
          <template #default="scope">
            <p> {{
              scope.row.goods?.shop_id
                ? storeData.find((item: any) => item.id == scope.row.goods.shop_id)?.title ?? '暂无'
                : '暂无'
            }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="user.name" label="用户名称" align="center">
          <template #default="scope">
            <p>{{ !scope.row.user.name ? "暂无" : scope.row.user.name }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="订单号" align="center" width="200" />
        <el-table-column prop="handle_money" label="总价格" align="center" />
        <el-table-column prop="num" label="总数量" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <span v-html="filterState(scope.row.status)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="购买时间" align="center" width="180" />
      </el-table>
      <div class="custom_container">
        <el-pagination @size-change="pageNum" @current-change="pageChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="sizes, prev, pager, next, jumper"
          :total="pageData.length" class="custom_pagination" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { larkOrder } from '/@/api/lark/lark_order/index';
// 导入店铺列表
import { larkShopList  } from '/@/api/lark/lark_shop/index';
import { ElMessage } from 'element-plus';

// 店铺列表
const storeData = ref<FoodType[]>([]);
const data = ref<OrderItem[]>([]);
const pageData = ref<OrderItem[]>([]);
// 分页页数
const currentPage = ref(1);
// 一页的数据
const pageSize = ref(10);
// 弹窗状态
const detailsState = ref(false);
// 弹窗数据
const detailsData = ref<any>({});
// 定义数据接口
interface OrderItem {
  title: string;
  createtime: any;
  detail: any;
  goods: any;
  status: any;
  user: any;
  // 其他字段可根据实际结构补充
}
// 店铺数据定义
interface FoodType {
  id: number;
  title: string;
  createtime: string;
}

const search = reactive({
  title: '',
  time: [],
})

const detailsForm = reactive({
  name: '',
  time: [],
  num: '',
  tel: '',
  price: '',
})

const getData = () => {
  larkOrder({ uid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id }).then((res) => {
    data.value = res.data;
    pageData.value = res.data;
    getStore();
  });
};
getData();

// 店铺列表接口
const getStore = () => {
  larkShopList({ uid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id }).then((res: any) => {
    storeData.value = res.data;
  });
}

// 计算当前页码的起始索引和结束索引，并返回对应区间的数据
const pageCount = computed(() => {
  // 计算起始索引，基于当前页码和每页大小
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});
/* 分页改变 */
const pageChange = (val: number) => {
  currentPage.value = val;
};
/* 分页大小改变 */
const pageNum = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 获取全选的id
const selectedIds = ref<any[]>([]);
const checkall = (val: any) => {
  selectedIds.value = val.map((item: any) => item.id).filter((id: number) => id);
};
// 详情弹窗显示
const detailShow = (item: any) => {
  detailsData.value = item.detail;
  setTimeout(() => {
    detailsState.value = true;
  }, 100);
  console.log(item.detail[0].num);
  detailsForm.name = item.user.name;
  detailsForm.tel = item.user.username;
  detailsForm.num = item.detail[0].num;
  detailsForm.time = item.createtime;
  detailsForm.price = item.money;
}

const filterState = (item: any) => {
  if (item == 1) {
    return `<p class="non_payment">待付款</p>`;
  } else if (item == 2) {
    return `<p class="non_written_off">待核销</p>`;
  } else if (item == 3) {
    return `<p class="Written_off">已核销</p>`;
  } else if (item == 4) {
    return `<p class="Canceled">已取消</p>`;
  } else {
    return `<p class="">暂无</p>`;
  }
}

const prompt = () => {
  ElMessage({
    message: '正在开发中！',
    type: 'warning',
  })
}

const checkedStatus = ref(0);
const filterData = (status: number) => {
  checkedStatus.value = status; // 只更新状态，不直接过滤数据
  searchData(); // 触发统一筛选
};

// 搜索函数
const searchData = () => {
  pageData.value = data.value;
  const filteredData = () => {
    // 无搜索词时返回全部数据
    if (search.title == '' && search.time.length == 0 && checkedStatus.value == 0) {
      return (pageData.value = data.value);
    }
    console.log(search.title);

    return pageData.value.filter((item) => {
      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch =
        !search.title || (item?.user?.name?.toLowerCase().includes(search.title.toLowerCase() ?? ''));
      const timeMatch =
        search.time.length == 0 ||
        (item.createtime >= search.time[0] && item.createtime <= search.time[1]);
      const statusMatch = checkedStatus.value === 0 || item.status == checkedStatus.value;
      return nameMatch && timeMatch && statusMatch;
    });
  };
  pageData.value = filteredData();
};
</script>

<style scoped>
.body {
  padding: 30px;
}

.content {
  position: relative;
  padding: 30px;
  background-color: white;
}

.line {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin: 20px 0;
}

.search_form {
  width: 100%;
  display: flex;
  margin-bottom: -22px;
}

.search_input {
  width: 240px;
  margin-right: 30px;
}

.input_height {
  height: 33px;
}

.button_height {
  height: 30px;
}

.operateBtn {
  display: flex;
  margin-top: 10px;
}

.btnGroup {
  width: 43%;
  display: flex;
  justify-content: space-between;
  margin-left: 60px;
}

.label {
  margin-top: 10px;
}

.operate_box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit {
  color: #409EFF;
  cursor: pointer;
  margin: 0px 10px;
}

.custom_container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.details {
  position: absolute;
  width: 100%;
  overflow: auto;
  background-color: white;
  top: 0;
  right: 0;
  z-index: 30;
}

.Pop_title {
  padding: 2%;
  border-bottom: 1px solid #ddd;
}

.details_box {
  display: flex;
  padding: 3%;
}

.user_form {
  width: 80%;
}

.user_title {
  width: 10%;
}

.user_input {
  display: flex;
  justify-content: space-around;
}

.info {
  display: flex;
  justify-content: space-between;
}

.non_payment {
  color: rgba(255, 165, 0, 1);
}

.non_written_off {
  color: rgba(64, 158, 255, 1);
}

.Weitten_off {
  color: rgba(124, 252, 0, 1);
}

.Canceled {
  color: rgba(128, 128, 128, 1);
}

.footer_btn {
  display: flex;
  justify-content: end;
  margin-right: 5%;
  margin-bottom: 2%;
}
</style>